/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package guzik.lukasz.snpexplorer;

import SnpDbEntities.Category;
import SnpDbEntities.Snippet;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.TreePath;

/**
 *
 * @author Łukasz 'byku' Guzik
 */
class ExtendedTreeCellRenderer extends DefaultTreeCellRenderer
{
    private Dimension defaultPrefferedSize = null;
    private Font defaultFont = null;

    public ExtendedTreeCellRenderer()
    {
    }

    @Override
    public Component getTreeCellRendererComponent(
	    JTree tree,
	    Object value,
	    boolean sel,
	    boolean expanded,
	    boolean leaf,
	    int row,
	    boolean hasFocus)
    {

	super.getTreeCellRendererComponent(
		tree, value, sel,
		expanded, leaf, row,
		hasFocus);

	if(defaultFont == null)
	{
	    defaultPrefferedSize = getPreferredSize();
	    defaultFont = getFont();
	}

	TreePath path = tree.getPathForRow(row);
	DefaultMutableTreeNode node;
	if(path != null)
	{
	    node = (DefaultMutableTreeNode) tree.getPathForRow(row).getLastPathComponent();
	    if(node.getUserObject() instanceof Category)
	    {
		this.setFont(getFont().deriveFont(Font.BOLD));
	    } else
	    {
		this.setFont(defaultFont);
	    }

	    calculatePrefferedSize(node.getUserObject());
	}

	return this;
    }

    private Dimension calculatePrefferedSize(Object userObject)
    {
	FontMetrics fontMetrics = getFontMetrics(getFont());
	String name;

	if(userObject instanceof Category)
	{
	    name = ((Category) userObject).getName();
	} else if(userObject instanceof Snippet)
	{
	    name = ((Snippet) userObject).getName();
	} else
	{
	    return defaultPrefferedSize;
	}

	return new Dimension(fontMetrics.stringWidth(name), defaultPrefferedSize.height);
    }
}
